import React, {useState} from 'react';
import {Form, Button, Divider, message} from 'antd';
import {connect} from 'umi';
import styles from './index.less';
import {UploadCommodityPicture, uploadCommodityStep} from '../../service';
import PicturesWall from './Upload';

const lableStyle = {
  labelCol: {span: 4},
  wrapperCol: {span: 24},
};

const Step2 = (props) => {
  const [form] = Form.useForm();
  const {data, dispatch, handleCurrent, CommodityId, complete} = props;
  const [imgs, setImgs] = useState([]);
  if (!data) {
    return null;
  }
  const {getFieldsValue} = form;

  const onPrev = () => {
    if (dispatch) {
      const values = getFieldsValue();
      handleCurrent(0);
      dispatch({
        type: 'commodityManagementAndCommodityCreatingSteps/saveStepFormData',
        payload: {...data, ...values},
      });
      dispatch({
        type: 'commodityManagementAndCommodityCreatingSteps/saveCurrentStep',
        payload: 'info',
      });
    }
  };
  const onValidateForm = async () => {
    let params = imgs.map(img=>{
      return {
        goodsId:CommodityId,
        url:img.url
      }
    });
    if (params.length === 0){
      params = [{
        goodsId:CommodityId,
      }];
    }
    UploadCommodityPicture(params, 'PUT').then((res) => {
      if (res.code === 0) {
        uploadCommodityStep(CommodityId, 0);
        complete(false);
      } else {
        message.error(res.message);
      }
    }).catch((err) => {
      console.log(err);
    });
  };

  const handleSetFacePicture = async (imgs) => {
    setImgs(imgs);
  };

  return (
    <Form {...lableStyle} form={form} layout="horizontal" className={styles.stepForm}>
      <Form.Item label="赠品图片" name="picture" required={false} className={styles.picture}>
        {CommodityId ? (
          <PicturesWall
            subpath="giveaway"
            handleSetFacePicture={handleSetFacePicture}
            CommodityId={CommodityId}
          />
        ) : null}
      </Form.Item>
      <Form.Item
        className={styles.bottomBtn}
        style={{
          marginBottom: 8,
        }}
        wrapperCol={{
          xs: {
            span: 24,
            offset: 0,
          },
        }}
      >
        <Button onClick={onPrev}>上一步</Button>
        <Divider type="vertical"/>
        <Button type="primary" onClick={onValidateForm}>
          完成
        </Button>
      </Form.Item>
    </Form>
  );
};

export default connect(({commodityManagementAndCommodityCreatingSteps, loading}) => ({
  submitting: loading.effects['commodityManagementAndCommodityCreatingSteps/submitStepForm'],
  data: commodityManagementAndCommodityCreatingSteps.step,
}))(Step2);
